import bpy
from bpy.types import Operator

class Draw_Panel_Op(Operator):
    bl_idname = "object.draw_panel"
    bl_label = "draw panel"
    bl_description = "draw a panel"

    # Settings
    rows = 2
    columns = 2
    size = 1
    

    # Utility functions
    def vert(self,column,row):
        """ Create a single vert """

        return (column * self.size, row * self.size, 0)


    def face(self,column,row):
        """ Create a single face """

        return (column* self.rows + row,
            (column + 1) * self.rows + row,
            (column + 1) * self.rows + 1 + row,
            column * self.rows + 1 + row)
    
    def execute(self,context):
        name = 'Gridtastic'
        
        # Looping to create the grid
        verts = [self.vert(x, y) for x in range(self.columns) for y in range(self.rows)]
        faces = [self.face(x, y) for x in range(self.columns - 1) for y in range(self.rows - 1)]

        # Create Mesh Datablock
        mesh = bpy.data.meshes.new(name)
        mesh.from_pydata(verts, [], faces)

        # Create Object and link to scene
        obj = bpy.data.objects.new(name, mesh)
        bpy.context.scene.collection.objects.link(obj)

        # Select the object
        bpy.context.view_layer.objects.active = obj
        obj.select_set(True)
            
        return {'FINISHED'}